<!DOCTYPE HTML>
<html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
	<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://cdn.bootcss.com/zTree.v3/3.5.33/js/jquery.ztree.core.min.js"></script>
	<link href="https://cdn.bootcss.com/zTree.v3/3.5.33/css/zTreeStyle/zTreeStyle.min.css" rel="stylesheet">
	<style>
		.trg {
			width: 0;
			height: 0;
			border-left: 3px solid transparent;
			border-right: 3px solid transparent;
			border-top: 6px solid black;
		;
			position: absolute;
			left: 140px;
			top: 8px;
		}

		.org-select {
			cursor: default;
			z-index: -1;
			width: 150px;
			border: 1px solid #ccc;
			background-color: white;
		}
		.categories{
			z-index: 100;
			background-color: #00a0e9;
		}
	</style>
<!--[if lt IE 9]>
<script type="text/javascript" src="js/html5.js"></script>
<script type="text/javascript" src="js/respond.min.js"></script阿迪>
<script type="text/javascript" src="js/PIE_IE678.js"></script>
<![endif]-->
<link th:href="@{/erp/assets/css/bootstrap.min.css}" rel="stylesheet" />
<link rel="stylesheet" th:href="@{/erp/css/style.css}"/>
<link th:href="@{/erp/assets/css/codemirror.css}" rel="stylesheet">
<link rel="stylesheet" th:href="@{/erp/assets/css/ace.min.css}" />
      <link rel="stylesheet" th:href="@{/erp/Widget/zTree/css/zTreeStyle/zTreeStyle.css}" type="text/css">
<link rel="stylesheet" th:href="@{/erp/assets/css/font-awesome.min.css}" />
<!--[if IE 7]>
		  <link rel="stylesheet" th:href="@{/erp/assets/css/font-awesome-ie7.min.css}" />
		<![endif]-->
<link th:href="@{/erp/Widget/icheck/icheck.css}" rel="stylesheet" type="text/css" />
<link th:href="@{/erp/Widget/webuploader/0.1.5/webuploader.css}" rel="stylesheet" type="text/css" />

<title>编辑商品</title>
</head>
<body>
   <div class="page_right_style">
   
	<form action="/products/updateProduct" method="post" class="form form-horizontal" id="form-article-add">
			<input type="hidden" name="id" th:value="${product.id}">
		<div class=" clearfix cl">
			<div class="Add_p_s">
            <label class="form-label col-2">商品名称：</label>
			<div class="formControls col-2"><input type="text"  class="input-text" th:value="${product.pName}"  placeholder="" id="pName" name="pName" onblur="pNames()"></div>
            </div>
			<div class="Add_p_s">
            <label class="form-label col-2">商品编号：</label>
			<div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pNumber}" placeholder="" id="pNumber" name="pNumber" onblur="pNumbers()"></div>
            </div>
			<div class="Add_p_s">
				<label class="form-label col-2">价&nbsp;&nbsp;&nbsp;&nbsp;格：</label>
				<div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pPrice}" placeholder="" id="pPrice" name="pPrice" onblur="Pricesa()"></div>
			</div>
			<div class="Add_p_s">
             <label class="form-label col-2">产&nbsp;&nbsp;&nbsp;&nbsp;地：</label>	
			 <div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pLocal}" placeholder="" id="pLocal" name="pLocal" onblur="Locals()"></div>
			</div>
            <div class="Add_p_s">
             <label class="form-label col-2">材&nbsp;&nbsp;&nbsp;&nbsp;质：</label>	
			 <div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pMaterial}" placeholder="" id="pMaterial" name="pMaterial" onblur="Material()"></div>
			</div>
            <div class="Add_p_s">
             <label class="form-label col-2">品&nbsp;&nbsp;&nbsp;&nbsp;牌：</label>	
			 <div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pBrand}" placeholder="" id="pBrand" name="pBrand" onblur="Brand()"></div>
			</div>
             <div class="Add_p_s">
             <label class="form-label col-2">商品质量：</label>	
			 <div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pQuality}" placeholder="" id="pQuality" name="pQuality" onblur="Quality()">kg</div>
			</div>
			  <div class="Add_p_s">
				  <label class="form-label col-2">分类(企业)：</label>
				  <div style="position: relative;margin:1px 40px 40px 105px;" class="categories">
					  <input id="orgName" class="org-select" onclick="showTree()" readonly name="name" onblur="names()" th:value="${product.name}">
					  <!-- 模拟select点击框 以及option的text值显示-->
					  <i class="trg" style="position: absolute;"></i>
					  <!-- 模拟select右侧倒三角 -->
					  <input id="orgCode" type="hidden" name="orgCode" />
					  <!-- 存储 模拟select的value值 -->
					  <!-- zTree树状图 相对定位在其下方 -->
					  <div class="ztree" style="display:none; position: absolute;border:1px solid #4aa5ff;width:150px;">
						  <ul id="treeDemo"></ul>
					  </div>
				  </div>
			  </div>
			    <div class="Add_p_s">
             <label class="form-label col-2">保质期：</label>
			 <div class="formControls col-2"><input type="text" class="input-text" th:value="${product.pShelflife}" placeholder="" id="pShelflife" name="pShelflife" onblur="Shelflife()">年</div>
			</div>
		</div>

		<div class="clearfix cl">
			<label class="form-label col-2">自定义属性:</label>
			<input type='button' class="btn btn-success radius" value='添加属性' onClick="fun()"/>
			<div class="formControls col-2">
				<div id="test1">
					<span class="size" th:each="productattribute,productattributeStat: ${product.productAttributeList}" th:value="${productattributeStat.size}">
					<input type="text"  th:value="${productattribute.pNames}" th:attr="name='productAttributeList['+${productattributeStat.index}+'].pNames'" size="5"/>&nbsp;&nbsp;:&nbsp;&nbsp;<input type="text" th:value="${productattribute.pValue}" th:attr="name='productAttributeList['+${productattributeStat.index}+'].pValue'" size="10"/><span style="color:#FF0000">&nbsp;&nbsp;(如：尺寸：2cm )</span>
					<br><br>
					</span>
				</div>
			</div>
		</div>

		<div class="clearfix cl">
			 <label class="form-label col-2">备注摘要：</label>
				<div class="formControls col-10">
					<script id="editor" type="text/plain" style="width:100%;height:300px;" name="pRemarks">
					</script>
				 </div>
			</div>

		<div class="clearfix cl">
			<label class="form-label col-2">修改图片：</label>
			<div class="formControls col-10">
				<div class="uploader-list-container"> 
					<div class="queueList">
						<div id="dndArea" class="placeholder">
							<div id="filePicker-2"></div>
							<p>或将照片拖到这里，单次最多可选300张</p>
						</div>
					</div>
					<div class="statusBar" style="display:none;">
						<div class="progress"> <span class="text">0%</span> <span class="percentage"></span> </div>
						<div class="info"></div>
						<div class="btns">
							<div id="filePicker2"></div>
							<div class="uploadBtn">开始上传</div>
						</div>
					</div>
				</div>
			</div>
		</div>
       
		<div class="clearfix cl" align="center">
			<div class="Button_operation">
<!--
				<button onClick="javascrtpt:window.location.href='Products_info.html'" class="btn btn-primary radius" type="button">确认修改</button>
-->
				<input type="submit" value="确认添加" class="btn btn-primary radius">

				<input type="reset" value="重新填写"  class="btn btn-success radius"/>
				
				<input type="button" name="Submit" class="btn btn-warning radius" onClick="javascript:history.back(-1);" value="返回上页">
			</div>
		</div>
	</form>
    </div>
	<input hidden="hidden" th:value="${product.pRemarks}" id="premarks">
</div>
<script th:src="@{/erp/js/jquery-1.9.1.min.js}"></script>
<script th:src="@{/erp/assets/js/bootstrap.min.js}"></script>
<script th:src="@{/erp/assets/js/typeahead-bs2.min.js}"></script>
<script th:src="@{/erp/assets/layer/layer.js}" type="text/javascript" ></script>
<script th:src="@{/erp/assets/laydate/laydate.js}" type="text/javascript"></script>
<script type="text/javascript" th:src="@{/erp/Widget/My97DatePicker/WdatePicker.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/icheck/jquery.icheck.min.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/zTree/js/jquery.ztree.all-3.5.min.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/Validform/5.3.2/Validform.min.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/webuploader/0.1.5/webuploader.min.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/ueditor/1.4.3/ueditor.config.js}"></script>
<script type="text/javascript" th:src="@{/erp/Widget/ueditor/1.4.3/ueditor.all.min.js}"> </script>
<script type="text/javascript" th:src="@{/erp/Widget/ueditor/1.4.3/lang/zh-cn/zh-cn.js}"></script>
<script th:src="@{/erp/js/lrtk.js}" type="text/javascript" ></script>
<script type="text/javascript" th:src="@{/erp/js/H-ui.js}"></script>
<script type="text/javascript" th:src="@{/erp/js/H-ui.admin.js}"></script>
<script>
	function check(){
		return pNames() && pNumbers() && Pricesa() && Material() && Locals() && Brand() && Quality() && Shelflife();
	}
	function pNames() {
		var names=/[^\w\u4E00-\u9FA5]/g;
		var pName=$('#pName').val();
		if(!names.test(pName)){
			$('#pName').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pName').attr('style','border:1px solid red');
			layer.msg("商品名称格式不对", {icon: 2, time: 2000});
			return false;
		}
	}
	function pNumbers() {
		var number=/^-?\d+$/;
		var pNumber=$('#pNumber').val();
		if(number.test(pNumber)){
			$.ajax({
				url : '/products/findNumber',
				type : 'post',
				data : {
					pNumber : pNumber
				},
				dataType : 'json',
				success : function (data) {
					if(data){
						$('#pNumber').attr('style','border:1px solid red');
						layer.msg("商品编号已存在", {icon: 2, time: 2000});
						return false;
					}else{
						$('#pNumber').attr('style','border:1px solid #ccc');
						return true;
					}
				}
			})
		}else{
			$('#pNumber').attr('style','border:1px solid red');
			layer.msg("商品编号为数字", {icon: 2, time: 2000});
			return false;
		}
	}
	function Pricesa() {
		var prices=/^[-\+]?\d+(\.\d*)?|\.\d+$/;
		var pPrices=$('#pPrice').val();
		if(prices.test(pPrices)){
			$('#pPrice').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pPrice').attr('style','border:1px solid red');
			layer.msg("价格为整数或小数", {icon: 2, time: 2000});
			return false;
		}
	}
	function Material() {
		var pMaterial=$('#pMaterial').val();
		if(pMaterial !==''){
			$('#pMaterial').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pMaterial').attr('style','border:1px solid red');
			layer.msg("材质不能为空", {icon: 2, time: 2000});
			return false;
		}
	}
	function names() {
		var names=$('#orgName').val();
		if(names !==''){
			$('#orgName').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#orgName').attr('style','border:1px solid red');
			layer.msg("分类名不能为空", {icon: 2, time: 2000});
			return false;
		}
	}
	function Locals() {
		var locals=/^[a-zA-Z\u4e00-\u9fa5]+$/;
		var pLocal=$('#pLocal').val();
		if(locals.test(pLocal)){
			$('#pLocal').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pLocal').attr('style','border:1px solid red');
			layer.msg("产地格式不正确", {icon: 2, time: 2000});
			return false;
		}
	}
	function Brand() {
		var pBrand=$('#pBrand').val();
		if(pBrand !==''){
			$('#pBrand').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pBrand').attr('style','border:1px solid red');
			layer.msg("品牌不能为空", {icon: 2, time: 2000});
			return false;
		}
	}
	function Quality() {
		var quality=/^[-\+]?\d+(\.\d*)?|\.\d+$/;
		var pQuality=$('#pQuality').val();
		if(quality.test(pQuality)){
			$('#pQuality').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pQuality').attr('style','border:1px solid red');
			layer.msg("质量为小数或整数", {icon: 2, time: 2000});
			return false;
		}
	}
	function Shelflife() {
		var shelflife=/^[-\+]?\d+(\.\d*)?|\.\d+$/;
		var pShelflife=$('#pShelflife').val();
		if(shelflife.test(pShelflife)){
			$('#pShelflife').attr('style','border:1px solid #ccc');
			return true;
		}else{
			$('#pShelflife').attr('style','border:1px solid red');
			layer.msg("保质期为整数或小数", {icon: 2, time: 2000});
			return false;
		}
	}
function change(v){
	var  show1div_display= document.getElementById('show1').style.display;
	var  show2div_display= document.getElementById('show2').style.display;
	var  show3div_display= document.getElementById('show3').style.display;
	
	if(v == 1){ 
		document.getElementById('show1').style.display='none';
		document.getElementById('show2').style.display='block';
		document.getElementById('show3').style.display='block';
	}else if(v == 2){
		document.getElementById('show1').style.display='block';
		document.getElementById('show2').style.display='none';
		document.getElementById('show3').style.display='none';
	}else {
		document.getElementById('show1').style.display='none';
		document.getElementById('show2').style.display='none';
		document.getElementById('show3').style.display='none';
		}
}
let sizes;
	if($(".size").attr("value")==undefined){
		sizes=-1;
	}else{
		sizes=$(".size").attr("value")-1;
	}
function fun() {
	sizes++;
	$("#test1").parent().append($('<div><input type="text" name="productAttributeList['+sizes+'].pNames" size="5"/>&nbsp;&nbsp;:&nbsp;&nbsp;<input type="text" name="productAttributeList['+sizes+'].pValue" size="10"/>&nbsp;&nbsp;<a onclick="move(this)" href="javascript:;"  >清除</a>&nbsp;&nbsp;&nbsp;<a onclick="clear_one(this)" href="javascript:;" >重写</a><br><br></div>'));
}

function move(that) {
	sizes--;
	$(that).parent().hide();
}

function clear_one(that) {
	$(that).siblings(":text").val("");
}
$(function() {
	$("#add_picture").fix({
		float : 'left',
		skin : 'green',	
		durationTime :false,
		stylewidth:'220',
		spacingw:0,
		spacingh:260,
	});
});
$( document).ready(function(){
//初始化宽度、高度
  
   $(".widget-box").height($(window).height()); 
   $(".page_right_style").height($(window).height()); 
   $(".page_right_style").width($(window).width()-220); 
  //当文档窗口发生改变时 触发  
    $(window).resize(function(){

	 $(".widget-box").height($(window).height()); 
	 $(".page_right_style").height($(window).height()); 
	 $(".page_right_style").width($(window).width()-220); 
	});	
});
$(function(){
	var ue = UE.getEditor('editor');
	ue.ready(function() {
		ue.setContent($('#premarks').val(), false);
	});
});
/******树状图********/
var setting = {
	data: {
		simpleData: {
			enable: true
		}
	},
	//回调
	callback: {
		onClick: zTreeOnClick
	},
	view: {
		fontCss: {
			fontSize: "14px"
		}
	},
	data: {
		simpleData: {
			enable: true,
			idKey: "id",
			pIdKey: "pid",
			rootPId: ""
		}
	},
};
//节点点击事件
function zTreeOnClick(event, treeId, treeNode) {
	$('#orgName').val(treeNode.name);
	$('#orgCode').val(treeNode.Id)
	hideTree();
};
$(document).ready(function() {
	//初始组织树状图
	$.ajax({
		url : '/categories/getCategoriess',
		type : 'post',
		contextType : 'application/Json',
		success:function (data) {
			$.fn.zTree.init($("#treeDemo"), setting, data);
		}
	})
});
//下拉框显示 隐藏
function showTree() {
	if($('.ztree').css('display') == 'none') {
		$('.ztree').css('display', 'block');
	} else {
		$('.ztree').css('display', 'none');
	}
	$("body").bind("mousedown", onBodyDownByActionType);
}

function hideTree() {
	$('.ztree').css('display', 'none');
	$("body").unbind("mousedown", onBodyDownByActionType);
	return false;
}

//区域外点击事件
function onBodyDownByActionType(event) {
	if(event.target.id.indexOf('treeDemo') == -1) {
		if(event.target.id != 'selectDevType') {
			hideTree();
		}
	}
}
</script>
<script type="text/javascript">
	$(function () {
		/*初始化uploader*/
		$list = $("#fileList"),
				$btn = $("#btn-star"),
				state = "pending",
				uploader;

		var uploader = WebUploader.create({
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.
			pick: '#filePicker',
			// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
			resize: false,
			// 只允许选择图片文件。
			accept: {
				title: 'Images',
				extensions: 'gif,jpg,jpeg,bmp,png',
				mimeTypes: 'image/*'
			}
		});
		uploader.on('fileQueued', function (file) {
			var $li = $(
					'<div id="' + file.id + '" class="item">' +
					'<div class="pic-box"><img></div>' +
					'<div class="info">' + file.name + '</div>' +
					'<p class="state">等待上传...</p>' +
					'</div>'
					),
					$img = $li.find('img');
			$list.append($li);

			// 创建缩略图
			// 如果为非图片文件，可以不用调用此方法。
			// thumbnailWidth x thumbnailHeight 为 100 x 100
			uploader.makeThumb(file, function (error, src) {
				if (error) {
					$img.replaceWith('<span>不能预览</span>');
					return;
				}

				$img.attr('src', src);
			}, thumbnailWidth, thumbnailHeight);
		});
		// 文件上传过程中创建进度条实时显示。
		uploader.on('uploadProgress', function (file, percentage) {
			var $li = $('#' + file.id),
					$percent = $li.find('.progress-box .sr-only');

			// 避免重复创建
			if (!$percent.length) {
				$percent = $('<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>').appendTo($li).find('.sr-only');
			}
			$li.find(".state").text("上传中");
			$percent.css('width', percentage * 100 + '%');
		});

		// 文件上传成功，给item添加成功class, 用样式标记上传成功。
		uploader.on('uploadSuccess', function (file) {
			$('#' + file.id).addClass('upload-state-success').find(".state").text("已上传");
		});

		// 文件上传失败，显示上传出错。
		uploader.on('uploadError', function (file) {
			$('#' + file.id).addClass('upload-state-error').find(".state").text("上传出错");
		});

		// 完成上传完了，成功或者失败，先删除进度条。
		uploader.on('uploadComplete', function (file) {
			$('#' + file.id).find('.progress-box').fadeOut();
		});
		uploader.on('all', function (type) {
			if (type === 'startUpload') {
				state = 'uploading';
			} else if (type === 'stopUpload') {
				state = 'paused';
			} else if (type === 'uploadFinished') {
				state = 'done';
			}

			if (state === 'uploading') {
				$btn.text('暂停上传');
			} else {
				$btn.text('开始上传');
			}
		});

		$btn.on('click', function () {
			if (state === 'uploading') {
				uploader.stop();
			} else {
				uploader.upload();
			}
		});

	});

	(function ($) {
		// 当domReady的时候开始初始化
		$(function () {
			var $wrap = $('.uploader-list-container'),

					// 图片容器
					$queue = $('<ul class="filelist"></ul>')
							.appendTo($wrap.find('.queueList')),

					// 状态栏，包括进度和控制按钮
					$statusBar = $wrap.find('.statusBar'),

					// 文件总体选择信息。
					$info = $statusBar.find('.info'),

					// 上传按钮
					$upload = $wrap.find('.uploadBtn'),

					// 没选择文件之前的内容。
					$placeHolder = $wrap.find('.placeholder'),

					$progress = $statusBar.find('.progress').hide(),

					// 添加的文件数量
					fileCount = 0,

					// 添加的文件总大小
					fileSize = 0,

					// 优化retina, 在retina下这个值是2
					ratio = window.devicePixelRatio || 1,

					// 缩略图大小
					thumbnailWidth = 110 * ratio,
					thumbnailHeight = 110 * ratio,

					// 可能有pedding, ready, uploading, confirm, done.
					state = 'pedding',

					// 所有文件的进度信息，key为file id
					percentages = {},
					// 判断浏览器是否支持图片的base64显示图片样式
					isSupportBase64 = (function () {
						var data = new Image();
						var support = true;
						data.onload = data.onerror = function () {
							if (this.width != 1 || this.height != 1) {
								support = false;
							}
						}
						data.src = "";
						return support;
					})(),

					// WebUploader实例
					uploader;

			// 实例化
			uploader = WebUploader.create({
				pick: {
					id: '#filePicker-2',
					label: '点击选择图片'
				},
				formData: {
					uid: 123
				},
				dnd: '#dndArea',
				paste: '#uploader',
				swf: '/static/erp/Widget/Uploader.swf',
				chunked: false,
				chunkSize: 512 * 1024,
				server: 'http://localhost:8080/productfile/fileUpload',

				// 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
				disableGlobalDnd: true,
				fileNumLimit: 300,
				fileSizeLimit: 200 * 1024 * 1024,    // 200 M
				fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
			});

			// 添加“添加文件”的按钮，
			uploader.addButton({
				id: '#filePicker2',
				label: '继续添加'
			});

			uploader.on('ready', function () {
				window.uploader = uploader;
			});

			// 当有文件添加进来时执行，负责view的创建
			function addFile(file) {
				var $li = $('<li id="' + file.id + '">' +
						'<p class="title">' + file.name + '</p>' +
						'<p class="imgWrap"></p>' +
						'<p class="progress"><span></span></p>' +
						'</li>'),

						$btns = $('<div class="file-panel">' +
								'<span class="cancel">删除</span>' +
								'<span class="rotateRight">向右旋转</span>' +
								'<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
						$prgress = $li.find('p.progress span'),
						$wrap = $li.find('p.imgWrap'),
						$info = $('<p class="error"></p>'),

						showError = function (code) {
							switch (code) {
								case 'exceed_size':
									text = '文件大小超出';
									break;

								case 'interrupt':
									text = '上传暂停';
									break;

								default:
									text = '上传失败，请重试';
									break;
							}

							$info.text(text).appendTo($li);
						};

				if (file.getStatus() === 'invalid') {
					showError(file.statusText);
				} else {
					// @todo lazyload
					$wrap.text('预览中');
					uploader.makeThumb(file, function (error, src) {
						var img;

						if (error) {
							$wrap.text('不能预览');
							return;
						}

						if (isSupportBase64) {
							img = $('<img src="' + src + '">');
							$wrap.empty().append(img);
						} else {
							$.ajax('http://localhost:8080/productfile/fileUpload', {
								method: 'POST',
								data: src,
								dataType: 'json'
							}).done(function (response) {
								if (response.result) {
									img = $('<img src="' + response.result + '">');
									$wrap.empty().append(img);
								} else {
									$wrap.text("预览出错");
								}
							});
						}
					}, thumbnailWidth, thumbnailHeight);

					percentages[file.id] = [file.size, 0];
					file.rotation = 0;
				}

				file.on('statuschange', function (cur, prev) {
					if (prev === 'progress') {
						$prgress.hide().width(0);
					} else if (prev === 'queued') {
						$li.off('mouseenter mouseleave');
						$btns.remove();
					}

					// 成功
					if (cur === 'error' || cur === 'invalid') {
						showError(file.statusText);
						percentages[file.id][1] = 1;
					} else if (cur === 'interrupt') {
						showError('interrupt');
					} else if (cur === 'queued') {
						percentages[file.id][1] = 0;
					} else if (cur === 'progress') {
						$info.remove();
						$prgress.css('display', 'block');
					} else if (cur === 'complete') {
						$li.append('<span class="success"></span> <input type="hidden" name="pImg" value="'+file.name+'">');
					}

					$li.removeClass('state-' + prev).addClass('state-' + cur);
				});

				$li.on('mouseenter', function () {
					$btns.stop().animate({height: 30});
				});

				$li.on('mouseleave', function () {
					$btns.stop().animate({height: 0});
				});

				$btns.on('click', 'span', function () {
					var index = $(this).index(),
							deg;

					switch (index) {
						case 0:
							uploader.removeFile(file);
							return;

						case 1:
							file.rotation += 90;
							break;

						case 2:
							file.rotation -= 90;
							break;
					}

					if (supportTransition) {
						deg = 'rotate(' + file.rotation + 'deg)';
						$wrap.css({
							'-webkit-transform': deg,
							'-mos-transform': deg,
							'-o-transform': deg,
							'transform': deg
						});
					} else {
						$wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
					}


				});

				$li.appendTo($queue);
			}

			// 负责view的销毁
			function removeFile(file) {
				var $li = $('#' + file.id);

				delete percentages[file.id];
				updateTotalProgress();
				$li.off().find('.file-panel').off().end().remove();
			}

			function updateTotalProgress() {
				var loaded = 0,
						total = 0,
						spans = $progress.children(),
						percent;

				$.each(percentages, function (k, v) {
					total += v[0];
					loaded += v[0] * v[1];
				});

				percent = total ? loaded / total : 0;

				spans.eq(0).text(Math.round(percent * 100) + '%');
				spans.eq(1).css('width', Math.round(percent * 100) + '%');
				updateStatus();
			}

			function updateStatus() {
				var text = '', stats;

				if (state === 'ready') {
					text = '选中' + fileCount + '张图片，共' +
							WebUploader.formatSize(fileSize) + '。';
				} else if (state === 'confirm') {
					stats = uploader.getStats();
					if (stats.uploadFailNum) {
						text = '已成功上传' + stats.successNum + '张照片至XX相册，' +
								stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
					}

				} else {
					stats = uploader.getStats();
					text = '共' + fileCount + '张（' +
							WebUploader.formatSize(fileSize) +
							'），已上传' + stats.successNum + '张';

					if (stats.uploadFailNum) {
						text += '，失败' + stats.uploadFailNum + '张';
					}
				}

				$info.html(text);
			}

			function setState(val) {
				var file, stats;

				if (val === state) {
					return;
				}

				$upload.removeClass('state-' + state);
				$upload.addClass('state-' + val);
				state = val;

				switch (state) {
					case 'pedding':
						$placeHolder.removeClass('element-invisible');
						$queue.hide();
						$statusBar.addClass('element-invisible');
						uploader.refresh();
						break;

					case 'ready':
						$placeHolder.addClass('element-invisible');
						$('#filePicker2').removeClass('element-invisible');
						$queue.show();
						$statusBar.removeClass('element-invisible');
						uploader.refresh();
						break;

					case 'uploading':
						$('#filePicker2').addClass('element-invisible');
						$progress.show();
						$upload.text('暂停上传');
						break;

					case 'paused':
						$progress.show();
						$upload.text('继续上传');
						break;

					case 'confirm':
						$progress.hide();
						$('#filePicker2').removeClass('element-invisible');
						$upload.text('开始上传');

						stats = uploader.getStats();
						if (stats.successNum && !stats.uploadFailNum) {
							setState('finish');
							return;
						}
						break;
					case 'finish':
						stats = uploader.getStats();
						if (stats.successNum) {
							layer.msg('上传成功', {icon: 6, time: 2000});
						} else {
							// 没有成功的图片，重设
							state = 'done';
							location.reload();
						}
						break;
				}

				updateStatus();
			}


			uploader.onFileQueued = function (file) {
				fileCount++;
				fileSize += file.size;

				if (fileCount === 1) {
					$placeHolder.addClass('element-invisible');
					$statusBar.show();
				}

				addFile(file);
				setState('ready');
				updateTotalProgress();
			};

			uploader.onFileDequeued = function (file) {
				fileCount--;
				fileSize -= file.size;

				if (!fileCount) {
					setState('pedding');
				}

				removeFile(file);
				updateTotalProgress();

			};

			uploader.on('all', function (type) {
				var stats;
				switch (type) {
					case 'uploadFinished':
						setState('confirm');
						break;

					case 'startUpload':
						setState('uploading');
						break;

					case 'stopUpload':
						setState('paused');
						break;

				}
			});

			uploader.onError = function (code) {
				alert('Eroor: ' + code);
			};

			$upload.on('click', function () {
				if ($(this).hasClass('disabled')) {
					return false;
				}

				if (state === 'ready') {
					uploader.upload();
				} else if (state === 'paused') {
					uploader.upload();
				} else if (state === 'uploading') {
					uploader.stop();
				}
			});
		});

	})(jQuery);
</script>
</body>
</html>